//
//  HomeTableViewController.swift
//  SinaWeibo
//
//  Created by Apple on 15/11/8.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
private let HomeCellId = "HomeCellId"
class HomeTableViewController: BaseTableViewController {
    //数据源
    private lazy var statuses = [Status]()
    override func viewDidLoad() {
        super.viewDidLoad()
        if !userLogin {
        visitorLoginView?.setUIInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            return
        }
        prepareTableView()
        loadData { (array) -> () in
            if array == nil{
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return
            }
            self.statuses = array!
            self.tableView.reloadData()
        }
    }
    //获取网络数据
    
    private func prepareTableView(){
        //注册Cell
        tableView.registerClass(StatusCell.self, forCellReuseIdentifier: HomeCellId)
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
    }
    //MARK:加载首页数据
    private func loadData(finished: (array: [Status]?) -> ()){
        let AFN = AFHTTPSessionManager()
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        guard let token = UserAccountViewModel().token else{
            SVProgressHUD.showErrorWithStatus("您暂未登陆")
            return
        }
        let parameters = ["access_token":token]
        AFN.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            guard let  dict = result as? [String : AnyObject] else{
                finished(array: nil)
                return
            }
//            print(result)
            if let array = dict["statuses"] as? [[String : AnyObject]]{
                var list = [Status]()
                for item in array {
                    let s = Status(dict: item)
                    list.append(s)
                }
                finished(array: list)
//                print(array)
            }
            }) { (_, error) -> Void in
                finished(array: nil)
                print(error)
        }
        
        
    }

}
//数据源方法及协议方法
extension HomeTableViewController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellId, forIndexPath: indexPath) as! StatusCell
        cell.status = statuses[indexPath.row]
        return cell
    }
}
